package cn.calm.dialog.action;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.struts2.osgi.interceptor.ServiceAware;

import cn.calm.commons.action.CurdAction;
import cn.calm.commons.entity.PageMode;
import cn.calm.dialog.service.IDialogService;
import cn.calm.entity.Button;
import cn.calm.entity.Dialog;

@SuppressWarnings("rawtypes")
public class DialogAction<T extends Dialog,S extends IDialogService<T>> extends
CurdAction<T,S> implements ServiceAware<IDialogService> {
	 /* 
	 */
	private static final long serialVersionUID = 1L;

	private static final Logger logger = Logger
			.getLogger(DialogAction.class);

	private String dialogs;
	private List<Button> buttons;

	@Override
	public String listPage() {
		logger.debug("listPage start");
		pageMode = service.listPage(pageMode, t, "id");
		logger.debug("listPage end");
		return "listPage";
	}

	@SuppressWarnings("unchecked")
	public String loadDep() {
		logger.debug("loadDep start");
		list = service.listInByProperty((Class<T>) Dialog.class, "id", dialogs.split(","));
		logger.debug("loadDep end");
		return "loadDep";
	}

	@Override
	public String update() {
		logger.debug("update start");
		try {
			if(buttons!=null){
				Set<Button> buts = new HashSet<Button>();
				buts.addAll(buttons);
				for (Button b : buts) {
					b.setDialog(t);
				}
				t.setButtons(buts);
			}
			return super.update();
		} finally {
			logger.debug("update end");
		}
	}

	@Override
	public String getModeName() {
		return "dialog";
	}

	public String getDialogs() {
		return dialogs;
	}

	public void setDialogs(String dialogs) {
		this.dialogs = dialogs;
	}

	@Override
	public List<T> getList() {
		return super.getList();
	}

	@Override
	public Map<String, List<String>> getFieldErrors() {
		return super.getFieldErrors();
	}

	@Override
	public Collection<String> getActionErrors() {
		return super.getActionErrors();
	}

	@Override
	public T getT() {
		return super.getT();
	}

	@Override
	public PageMode getPageMode() {
		return super.getPageMode();
	}

	public List<Button> getButtons() {
		return buttons;
	}

	public void setButtons(List<Button> buttons) {
		this.buttons = buttons;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setServices(List<IDialogService> services) {
		if (service == null) {
			if (services != null && services.size() > 0) {
				service = (S) services.get(0);
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Class<T> getEntityClass() {
		return (Class<T>) Dialog.class;
	}
}
